<template>
  <div class="order-detail-container">
    <!-- 顶部导航 -->
    <header class="detail-header">
      <button class="back-btn" @click="handleBack">
        <i class="fa fa-arrow-left"></i> 返回
      </button>
      <h2>订单详情</h2>
    </header>

    <!-- 调试信息显示（开发环境） -->
    <!-- <div v-if="showDebugInfo" class="debug-info">
      <p>订单ID: {{ order?.id }}</p>
      <p>当前状态: {{ order?.status }}</p>
      <p>用户身份: {{ userDetail.identity }}</p>
      <p>支付按钮可见性: {{ userDetail.identity === 3 && order?.status === 1 }}</p>
    </div> -->

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <i class="fa fa-circle-o-notch fa-spin"></i>
      <p>加载订单详情中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="!isLoading && errorMessage" class="error-state">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ errorMessage }}</p>
      <button class="reload-btn" @click="fetchOrderDetail">重新加载</button>
    </div>

    <!-- 订单详情内容 -->
    <div v-if="!isLoading && !errorMessage && order" class="detail-content">
      <!-- 订单基本信息 -->
      <div class="order-base-info">
        <div class="order-status-bar">
          <span class="status-label">订单状态：</span>
          <span 
            class="status-value"
            :class="getStatusClass(order.status)"
          >
            {{ getStatusText(order.status) }}
          </span>
        </div>
        
        <div class="order-meta">
          <p><span class="meta-label">订单编号：</span>{{ order.order_id || `ORDER-${order.id}` }}</p>
          <p><span class="meta-label">创建时间：</span>{{ formatTime(order.create_time) }}</p>
          <p><span class="meta-label">支付方式：</span>{{ getPayMethodText(order.pay_method) }}</p>
          <p v-if="order.store"><span class="meta-label">所属店铺：</span>{{ order.store_name }}</p>
        </div>
      </div>

      <!-- 收货信息 -->
      <div class="section recipient-section">
        <h3 class="section-title">收货信息</h3>
        <div class="recipient-info">
          <p><i class="fa fa-user"></i> {{ order.user_name || '匿名用户' }}</p>
          <p><i class="fa fa-phone"></i> {{ order.phone || '未填写手机号' }}</p>
          <p><i class="fa fa-map-marker"></i> {{ order.address || '未填写地址' }}</p>
        </div>
      </div>

      <!-- 商品清单 -->
      <div class="section commodity-section">
        <h3 class="section-title">商品清单</h3>
        <div class="commodity-list">
          <div 
            class="commodity-item" 
            v-for="(item, index) in order.order_details" 
            :key="index"
          >
            <span class="commodity-name">{{ item.commodity_name || `商品${index + 1}` }}</span>
            <div class="commodity-amount">
              <span class="count">×{{ item.number }}</span>
              <span class="price">¥{{ formatPrice(item.commodity_price) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单金额 -->
      <div class="amount-section">
        <div class="amount-item">
          <span class="amount-label">商品总价：</span>
          <span class="amount-value">¥{{ formatPrice(calculateTotal()) }}</span>
        </div>
        <div class="amount-item total">
          <span class="amount-label">订单总计：</span>
          <span class="amount-value">¥{{ formatPrice(order.sum) }}</span>
        </div>
      </div>

      <!-- 操作按钮区 -->
      <div class="action-section">
        <!-- 商家操作：确认出餐（状态2→3） -->
        <button 
          class="action-btn prepare-btn"
          @click="handlePrepareOrder"
          :disabled="isProcessing"
          v-if="userDetail.identity === 1 && order.status === 2"
        >
          <i class="fa fa-cutlery"></i> 
          <span v-if="isProcessing">处理中...</span>
          <span v-else>确认出餐</span>
        </button>

        <!-- 骑手操作：接单/完成配送（状态3→4→5） -->
        <button 
          class="action-btn accept-btn"
          @click="handleRiderOrder"
          :disabled="isProcessing"
          v-if="userDetail.identity === 2 && [3, 4].includes(order.status)"
        >
          <i class="fa fa-bicycle"></i> 
          <span v-if="isProcessing">处理中...</span>
          <span v-else-if="order.status === 3">接单配送</span>
          <span v-else>完成配送</span>
        </button>

        <!-- 用户操作：结算按钮（待支付状态） -->
        <button 
          class="action-btn pay-btn"
          @click="handlePayOrder"
          :disabled="isProcessing"
          v-if="userDetail.identity === 3 && order.status === 1"
          ref="payButton"
        >
          <i class="fa fa-money"></i> 
          <span v-if="isProcessing">处理中...</span>
          <span v-else>结算支付</span>
        </button>

        <!-- 用户操作：取消订单（状态1,2可取消） -->
        <button 
          class="action-btn cancel-btn"
          @click="handleCancelOrder"
          :disabled="isProcessing"
          v-if="userDetail.identity === 3 && [1, 2].includes(order.status)"
        >
          <i class="fa fa-times"></i> 
          <span v-if="isProcessing">处理中...</span>
          <span v-else>取消订单</span>
        </button>

        <!-- 用户操作：确认收货（状态5→6） -->
        <button 
          class="action-btn confirm-btn"
          @click="handleConfirmOrder"
          :disabled="isProcessing"
          v-if="userDetail.identity === 3 && order.status === 5"
        >
          <i class="fa fa-check"></i> 
          <span v-if="isProcessing">处理中...</span>
          <span v-else>确认收货</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

// 路由实例
const router = useRouter();
const route = useRoute();

// 调试用引用
const payButton = ref(null);
const showDebugInfo = ref(true); // 开发环境开启调试信息

// 状态管理
const state = reactive({
  // 基础状态
  isLoading: true,
  isProcessing: false,
  errorMessage: '',
  order: null,
  
  // 用户信息
  userDetail: {
    identity: null // 1:商家, 2:骑手, 3:用户
  },
  
  // 配置映射
  orderStatusMap: {
    '1': '待支付',
    '2': '待接单',
    '3': '待派送',
    '4': '派送中',
    '5': '待确认',
    '6': '完成',
    '7': '已取消'
  },
  statusClassMap: {
    '1': 'status-pending-pay',
    '2': 'status-pending-accept',
    '3': 'status-pending-deliver',
    '4': 'status-delivering',
    '5': 'status-completed',
    '6': 'status-canceled',
    '7': 'status-canceling'
  },
  payMethodMap: {
    '1': '支付宝',
    '2': '微信支付',
    '3': '货到付款'
  }
});

const {
  isLoading, isProcessing, errorMessage, order, userDetail,
  orderStatusMap, statusClassMap, payMethodMap
} = toRefs(state);

// 初始化
onMounted(() => {
  fetchUserIdentity();
  fetchOrderDetail();
  
  // 检查支付按钮是否正确渲染
  nextTick(() => {
    if (payButton.value) {
      console.log('支付按钮已正确渲染');
    } else {
      console.log('支付按钮未渲染，可能是条件不满足');
    }
  });
});

/**
 * 获取用户身份信息
 */
const fetchUserIdentity = async () => {
  try {
    const response = await axios.put('/user/user/info/');
    userDetail.value = response.data;
    console.log('获取用户身份成功:', userDetail.value);
  } catch (err) {
    console.error('获取用户身份失败:', err);
    errorMessage.value = '获取用户信息失败，请刷新页面重试';
  }
};

/**
 * 获取订单详情
 */
const fetchOrderDetail = async () => {
  try {
    isLoading.value = true;
    errorMessage.value = '';
    
    const orderId = route.params.id;
    const response = await axios.get(`/order/order/${orderId}/`);
    order.value = response.data;
    console.log('获取订单详情成功:', order.value);
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '获取订单详情失败，请重试';
    console.error('获取订单详情错误:', err);
  } finally {
    isLoading.value = false;
  }
};

/**
 * 处理订单支付 - 修复版
 */
const handlePayOrder = async () => {
  console.log('支付按钮被点击');
  
  if (!order.value || !order.value.id) {
    alert('订单信息不完整，无法支付');
    console.error('订单ID不存在:', order.value);
    return;
  }

  try {
    isProcessing.value = true;
    console.log('开始调用支付接口，订单ID:', order.value.id);
    
    // 调用支付接口获取支付宝支付链接
    const response = await axios.get(`/order/paymethods/${order.value.id}/pay/`);
    console.log('支付接口返回结果:', response.data);
    
    // 验证返回结果
    if (response.data && response.data.pay_url) {
      console.log('支付链接获取成功，跳转中:', response.data.pay_url);
      // 使用window.location.href确保跳转
      window.location.href = response.data.pay_url;
    } else {
      throw new Error('支付接口未返回有效的支付链接');
    }
  } catch (err) {
    console.error('支付过程错误详情:', err);
    // 详细的错误信息展示
    let errorMsg = '支付失败，请重试';
    if (err.response) {
      errorMsg = `支付失败: ${err.response.data.detail || err.response.statusText}`;
      console.error('接口错误响应:', err.response.data);
    } else if (err.message) {
      errorMsg = `支付失败: ${err.message}`;
    }
    alert(errorMsg);
  } finally {
    isProcessing.value = false;
  }
};

/**
 * 商家确认出餐
 */
const handlePrepareOrder = async () => {
  if (confirm('确定要确认出餐吗？订单状态将改为“待派送”')) {
    try {
      isProcessing.value = true;
      const orderId = order.value.id;
      
      // 调用商家出餐接口
      await axios.put(`/order/order/${orderId}/shop/order/`);
      
      // 更新本地订单状态
      order.value.status = 3; // 改为待派送
      alert('出餐确认成功！订单已转为待派送状态');
    } catch (err) {
      alert(err.response?.data?.message || '出餐确认失败，请重试');
      console.error('商家出餐接口错误:', err);
    } finally {
      isProcessing.value = false;
    }
  }
};

/**
 * 骑手接单/完成配送
 */
const handleRiderOrder = async () => {
  const currentStatus = order.value.status;
  const actionText = currentStatus === 3 ? '接单配送' : '完成配送';
  
  if (confirm(`确定要${actionText}吗？`)) {
    try {
      isProcessing.value = true;
      const orderId = order.value.id;
      
      // 调用骑手操作接口
      await axios.put(`/order/order/${orderId}/rider/order/`);
      
      // 更新本地订单状态
      order.value.status = currentStatus === 3 ? 4 : 5;
      alert(`${actionText}成功！`);
    } catch (err) {
      alert(err.response?.data?.detail || `${actionText}失败，请重试`);
      console.error('骑手操作接口错误:', err);
    } finally {
      isProcessing.value = false;
    }
  }
};

/**
 * 用户取消订单 - 跳转到退款页面
 */
const handleCancelOrder = () => {
  // 跳转到退款页面并携带订单ID
  router.push({
    path: `/order/${order.value.id}/cancel`,
    query: {
      sum: order.value.sum,
      status: order.value.status
    }
  });
};

/**
 * 用户确认收货
 */
const handleConfirmOrder = async () => {
  if (confirm('确定已收到商品吗？确认后订单将标记为已完成')) {
    try {
      isProcessing.value = true;
      const orderId = order.value.id;
      
      // 调用确认收货接口
      await axios.put(`/order/order/${orderId}/confirm/order/`);
      
      // 更新本地订单状态
      order.value.status = 6;
      alert('确认收货成功！订单已完成');
    } catch (err) {
      alert(err.response?.data?.detail || '确认收货失败，请重试');
      console.error('确认收货接口错误:', err);
    } finally {
      isProcessing.value = false;
    }
  }
};

/**
 * 计算商品总价（用于核对）
 */
const calculateTotal = () => {
  if (!order.value?.order_details || order.value.order_details.length === 0) {
    return 0;
  }
  
  return order.value.order_details.reduce((total, item) => {
    return total + (Number(item.commodity_price) * Number(item.number));
  }, 0);
};

/**
 * 工具函数：格式化时间
 */
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

/**
 * 工具函数：格式化价格
 */
const formatPrice = (price) => {
  const numericPrice = Number(price);
  return isNaN(numericPrice) ? '0.00' : numericPrice.toFixed(2);
};

/**
 * 工具函数：获取订单状态文本
 */
const getStatusText = (status) => {
  return orderStatusMap.value[status] || `未知状态(${status})`;
};

/**
 * 工具函数：获取订单状态样式
 */
const getStatusClass = (status) => {
  return statusClassMap.value[status] || 'status-unknown';
};

/**
 * 工具函数：获取支付方式文本
 */
const getPayMethodText = (method) => {
  return payMethodMap.value[method] || `未知方式(${method})`;
};

/**
 * 返回上一页
 */
const handleBack = () => {
  router.back();
};
</script>

<style scoped>
/* 调试信息样式 */
.debug-info {
  background-color: #fff3e0;
  padding: 10px;
  border: 1px solid #ffe0b2;
  margin: 10px;
  border-radius: 4px;
  font-size: 12px;
  color: #e65100;
}

/* 原有样式保持不变 */
.order-detail-container {
  min-height: 100vh;
  background-color: #f9f9f9;
  color: #333;
}

/* 头部导航 */
.detail-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #333;
  cursor: pointer;
  margin-right: 15px;
}

.detail-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 80px 0;
  color: #666;
}

.loading-state i {
  font-size: 40px;
  margin-bottom: 15px;
  color: #ff7a5a;
  animation: spin 1.5s linear infinite;
}

/* 错误状态 */
.error-state {
  background-color: #ffebee;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  color: #b71c1c;
  margin: 20px;
}

.error-state i {
  font-size: 40px;
  margin-bottom: 15px;
}

.error-state p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.reload-btn {
  background-color: #ff7a5a;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
}

/* 详情内容区 */
.detail-content {
  background-color: white;
  margin: 15px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

/* 订单基本信息 */
.order-base-info {
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.order-status-bar {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.status-label {
  font-size: 15px;
  color: #666;
}

.status-value {
  font-size: 16px;
  font-weight: 500;
  padding: 3px 10px;
  border-radius: 12px;
}

.order-meta {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.order-meta p {
  margin: 0;
  font-size: 14px;
}

.meta-label {
  color: #666;
}

/* 分区样式 */
.section {
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #555;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #ff7a5a;
  border-radius: 2px;
}

/* 收货信息 */
.recipient-info p {
  margin: 8px 0;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.recipient-info i {
  color: #999;
  width: 16px;
  text-align: center;
}

/* 商品清单 */
.commodity-list {
  border-radius: 4px;
  overflow: hidden;
}

.commodity-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #eee;
}

.commodity-item:last-child {
  border-bottom: none;
}

.commodity-name {
  flex: 1;
  font-size: 14px;
}

.commodity-amount {
  display: flex;
  align-items: center;
  gap: 15px;
}

.count {
  color: #666;
  font-size: 14px;
}

.price {
  color: #ff7a5a;
  font-weight: 500;
}

/* 金额信息 */
.amount-section {
  padding: 20px;
  background-color: #f9f9f9;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 14px;
}

.amount-item.total {
  font-size: 16px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.amount-label {
  color: #666;
}

.amount-value {
  color: #e53935;
  font-weight: bold;
}

/* 操作按钮区 */
.action-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.action-btn {
  padding: 10px 25px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  transition: all 0.3s;
}

.prepare-btn {
  background-color: #4caf50;
  color: white;
}

.prepare-btn:hover {
  background-color: #388e3c;
}

.accept-btn {
  background-color: #2196f3;
  color: white;
}

.accept-btn:hover {
  background-color: #1976d2;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
}

.cancel-btn:hover {
  background-color: #d32f2f;
}

.pay-btn {
  background-color: #ff9800;
  color: white;
}

.pay-btn:hover {
  background-color: #f57c00;
}

.confirm-btn {
  background-color: #4caf50;
  color: white;
}

.confirm-btn:hover {
  background-color: #388e3c;
}

.action-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 状态样式 */
.status-pending-pay {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-pending-accept {
  background-color: #fff8e1;
  color: #f57c00;
}

.status-pending-deliver {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-delivering {
  background-color: #e0f7fa;
  color: #00acc1;
}

.status-completed {
  background-color: #f1f8e9;
  color: #558b2f;
}

.status-canceled {
  background-color: #ffebee;
  color: #c62828;
}

.status-canceling {
  background-color: #fce4ec;
  color: #d81b60;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-meta {
    grid-template-columns: 1fr;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
